﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Data.SqlClient;

using ShoveEL.Alipay;

public partial class FinanceCenter_AdminDistillMoney : PageBase
{
    protected string gateway = "";
    protected string service = "";
    protected string partner = "";
    protected string sign_type = "";
    protected string _input_charset = "";                                                     //编码类型
    protected string digest_bptb_pay_file = "";                                               //文件摘要
    protected string file_digest_type = "";                                                   //文件摘要算法
    protected string biz_type = "";                                                           //业务类型
    protected string key = "";
    protected string agentID = "";                                                            //代理商ID
    protected string sign = "";                                                               //签名
    protected string bptb_pay_file = "";                                                      //上传的文件地址
    protected string Url = "";

    private DataTable dtExcel = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindData();

        if (!this.IsPostBack)
        {
            tbTime.Value = System.DateTime.Now.ToString();

            BindData1();

            BindData2();
        }
    }

    #region Web 窗体设计器生成的代码

    override protected void OnInit(EventArgs e)
    {
        isRequestLogin = true;
        RequestCompetences = Competences.BuildCompetencesList(Competences.Finance);
        RequestLoginPage = "FinanceCenter/AdminDistillMoney.aspx";

        base.OnInit(e);
    }

    #endregion

    private void BindData()
    {
        string Fields = "id,Name,RealityName,IDCardNumber,BankNameDetail,BankCardNumber,BankCardName,Balance,Earning,EarningBalanced,isSurrogate,Province,City";
        dtExcel = DAL.Views.V_Users.Select(Fields, "Earning - EarningBalanced > 0", "isSurrogate desc, [id]");

        if (dtExcel == null)
        {
            ShoveEL._Web.JavaScript.Alert(this.Page, "数据库连接失败");

            return;
        }

        g.DataSource = dtExcel;
        g.DataBind();
        gPager.Visible = (dtExcel.Rows.Count > 0);
        btnGOAll.Enabled = (dtExcel.Rows.Count > 0);
        btnGOAllOnlinPay.Enabled = (dtExcel.Rows.Count > 0);
    }

    protected void g_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
        {
            double Money = ShoveEL._Convert.StrToDouble(e.Item.Cells[6].Text, 0);
            e.Item.Cells[6].Text = Money.ToString("N");

            double Earning = ShoveEL._Convert.StrToDouble(e.Item.Cells[11].Text, 0);
            double EarningBalance = ShoveEL._Convert.StrToDouble(e.Item.Cells[12].Text, 0);
            e.Item.Cells[7].Text = (Earning - EarningBalance).ToString("N");
            ((TextBox)e.Item.Cells[8].FindControl("tbMoney")).Text = (Earning - EarningBalance).ToString();

            bool isSurrogate = ShoveEL._Convert.StrToBool(e.Item.Cells[10].Text, false);
            if (isSurrogate)
            {
                e.Item.BackColor = System.Drawing.Color.LightCyan;
                e.Item.ToolTip = "代理商";
            }
        }
    }

    protected void g_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        long UserID = ShoveEL._Convert.StrToLong(e.Item.Cells[9].Text, -1);

        string Return = "";
        int Result = 0;

        if (e.CommandName == "btnGO")
        {
            if (UserID < 0)
            {
                PublicFunction.GoError(ErrorNumber.Unknow, "数据参数错误", this.GetType().BaseType.FullName);

                return;
            }

            double EarningNoBalanced = ShoveEL._Convert.StrToDouble(e.Item.Cells[7].Text.Replace(",", ""), 0);
            double Money = ShoveEL._Convert.StrToDouble(((TextBox)e.Item.Cells[8].FindControl("tbMoney")).Text, 0);
            if ((Money < 0) || (Money > EarningNoBalanced))
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, "请输入有效的金额(不大于未结算奖金)。");
                return;
            }


            User tu = new User();
            tu.ID = UserID;
            Return = "";
            Result = tu.GetUserInfoByID(ref Return);
            if (Result < 0)
            {
                PublicFunction.GoError(ErrorNumber.DataReadWrite, "数据读写错误", this.GetType().BaseType.FullName);

                return;
            }

            if (tu.Balance < Money)
            {
                ShoveEL._Web.JavaScript.Alert(this, "用户帐户余额不足(帐户余额：" + tu.Balance.ToString() + " 元)。");

                return;
            }

            Result = 0;
            Return = "";

            if (DAL.Procedures.P_UserDistill.Call(tu.ID, Money, tu.BankNameDetail, tu.BankCardNumber, "奖金结算", 0, _User.ID, 1, -1, 1, ref Result, ref Return) < 0)
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, "结算失败");

                return;
            }

            if (Result < 0)
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, Return);

                return;
            }

            if (tu.ID == _User.ID)
            {
                _User.GetUserInfoByID(ref Return);
            }

            //写入操作日志
            OperationLog Log = new OperationLog();

            Log._Memo = _User.Name + "处理" + e.Item.Cells[15].Text.Trim() + "日薪（处理方式：线下转账）";
            Log._OpDateTime = DateTime.Now;
            Log._UserID = _User.ID;
            Log._UserIP = System.Web.HttpContext.Current.Request.UserHostAddress;

            Log.Add();
            //操作日志写入完成

            try
            {
                BindData();
            }
            catch
            {
                if (gPager.PageIndex > 0)
                {
                    gPager.PageIndex -= 1;
                    BindData();
                }
            }

            ShoveEL._Web.JavaScript.Alert(this, "此消费ID提款结算成功。", "AdminDistillMoney.aspx");

            return;
        }

        if (e.CommandName == "btnGOOnlinPay")
        {
            if (UserID < 0)
            {
                PublicFunction.GoError(ErrorNumber.Unknow, "数据参数错误", this.GetType().BaseType.FullName);

                return;
            }

            double EarningNoBalanced = ShoveEL._Convert.StrToDouble(e.Item.Cells[7].Text.Replace(",", ""), 0);
            double Money = ShoveEL._Convert.StrToDouble(((TextBox)e.Item.Cells[8].FindControl("tbMoney")).Text, 0);
            if ((Money < 0) || (Money > EarningNoBalanced))
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, "请输入有效的金额(不大于未结算奖金)。");

                return;
            }

            User tu = new User();
            tu.ID = UserID;
            Return = "";
            Result = tu.GetUserInfoByID(ref Return);
            if (Result < 0)
            {
                PublicFunction.GoError(ErrorNumber.DataReadWrite, "数据读写错误", this.GetType().BaseType.FullName);

                return;
            }

            if (tu.Balance < Money)
            {
                ShoveEL._Web.JavaScript.Alert(this, "用户帐户余额不足(帐户余额：" + tu.Balance.ToString() + " 元)。");

                return;
            }

            Result = 0;
            Return = "";

            if (DAL.Procedures.P_UserDistill.Call(tu.ID, Money, tu.BankNameDetail, tu.BankCardNumber, "奖金结算", 0, _User.ID, 0, -1, 1, ref Result, ref Return) < 0)
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, "结算失败");

                return;
            }

            if (Result < 0)
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, Return);

                return;
            }

            if (tu.ID == _User.ID)
            {
                _User.GetUserInfoByID(ref Return);
            }

            //写入操作日志
            OperationLog Log = new OperationLog();

            Log._Memo = _User.Name + "处理" + e.Item.Cells[15].Text.Trim() + "日薪（处理方式：在线转账）";
            Log._OpDateTime = DateTime.Now;
            Log._UserID = _User.ID;
            Log._UserIP = System.Web.HttpContext.Current.Request.UserHostAddress;

            Log.Add();
            //操作日志写入完成

            try
            {
                BindData();
            }
            catch
            {
                if (gPager.PageIndex > 0)
                {
                    gPager.PageIndex -= 1;
                    BindData();
                }
            }

            ShoveEL._Web.JavaScript.Alert(this, "此消费ID提款结算成功。", "AdminDistillMoney.aspx");

            return;
        }
    }

    protected void gPager_PageWillChange(object Sender, Shove.Web.UI.PageChangeEventArgs e)
    {
        BindData();
    }

    protected void gPager_SortBefore(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
        BindData();
    }

    protected void btnGOAll_Click(object sender, System.EventArgs e)
    {
        int Result = 0;
        string Return = "";

        if (DAL.Procedures.P_UserDistillAll.Call(_User.ID, 1, -1, 1, ref Result, ref Return) < 0)
        {
            ShoveEL._Web.JavaScript.Alert(this.Page, "结算失败");

            return;
        }

        if (Result < 0)
        {
            ShoveEL._Web.JavaScript.Alert(this.Page, Return);

            return;
        }

        //写入操作日志
        OperationLog Log = new OperationLog();

        Log._Memo = _User.Name + "处理所有用户日薪（处理方式：线下转账）";
        Log._OpDateTime = DateTime.Now;
        Log._UserID = _User.ID;
        Log._UserIP = System.Web.HttpContext.Current.Request.UserHostAddress;

        Log.Add();
        //操作日志写入完成

        Return = "";
        _User.GetUserInfoByID(ref Return);

        gPager.PageIndex = 0;
        BindData();

        ShoveEL._Web.JavaScript.Alert(this, "结算成功。", "AdminDistillMoney.aspx");
    }

    protected void btnGOAllOnlinPay_Click(object sender, System.EventArgs e)
    {
        int Result = 0;
        string Return = "";

        if (DAL.Procedures.P_UserDistillAll.Call(_User.ID, 0, -1, 1, ref Result, ref Return) < 0)
        {
            ShoveEL._Web.JavaScript.Alert(this.Page, "结算失败");

            return;
        }

        if (Result < 0)
        {
            ShoveEL._Web.JavaScript.Alert(this.Page, Return);

            return;
        }

        //写入操作日志
        OperationLog Log = new OperationLog();

        Log._Memo = _User.Name + "处理所有用户日薪（处理方式：在线转账）";
        Log._OpDateTime = DateTime.Now;
        Log._UserID = _User.ID;
        Log._UserIP = System.Web.HttpContext.Current.Request.UserHostAddress;

        Log.Add();
        //操作日志写入完成

        Return = "";
        _User.GetUserInfoByID(ref Return);

        gPager.PageIndex = 0;
        BindData();

        ShoveEL._Web.JavaScript.Alert(this, "结算成功。", "AdminDistillMoney.aspx");
    }

    private void BindData1()
    {
        DataTable dt = DAL.Views.V_UserDistills.Select("", "PaymentType = 0 and [Type] = 1 and Result = 0", "isSurrogate desc");

        if (dt == null)
        {
            ShoveEL._Web.JavaScript.Alert(this.Page, "数据库连接失败");

            return;
        }

        g1.DataSource = dt;
        g1.DataBind();

        gPager1.Visible = (dt.Rows.Count > 0);
        btnAlipayAdd.Enabled = (dt.Rows.Count > 0);
        btnAlipayToAlipayAdd.Enabled = (dt.Rows.Count > 0);
    }

    protected void g1_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
        {
            e.Item.Cells[2].Text += "(" + e.Item.Cells[13].Text + ")";

            double Money = ShoveEL._Convert.StrToDouble(e.Item.Cells[3].Text, 0);
            e.Item.Cells[3].Text = "￥" + Money.ToString("N");

            int Type = ShoveEL._Convert.StrToInt(e.Item.Cells[15].Text, 0);
            e.Item.Cells[5].Text = "日薪";
            e.Item.Cells[17].Text = "日薪";

            e.Item.Cells[18].Text = "2";    //对公对私标志 1 表示对公账号 2 表示对私账号
        }
    }

    protected void g1_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "btnToBank")
        {
            int CheckedCount = 0;
            double SumMoney = 0;
            string Body = "";

            double Money = 0;

            string UserDistillIDs = "";

            Money = ShoveEL._Convert.StrToDouble(e.Item.Cells[20].Text, 0);

            Body += e.Item.Cells[1].Text.Trim() + "," + e.Item.Cells[13].Text.Trim() + "," + e.Item.Cells[10].Text.Trim() + "," + e.Item.Cells[8].Text.Trim() + "," + e.Item.Cells[11].Text.Trim() + "," + e.Item.Cells[12].Text.Trim() + "," + e.Item.Cells[9].Text.Trim() + "," + Money.ToString() + "," + (ShoveEL._Convert.StrToBool(e.Item.Cells[18].Text.Trim(), true) ? "2" : "1") + "," + e.Item.Cells[17].Text.Trim() + "\r\n";

            if (UserDistillIDs == "")
            {
                UserDistillIDs = e.Item.Cells[1].Text.Trim();
            }
            else
            {
                UserDistillIDs += "," + e.Item.Cells[1].Text.Trim();
            }

            SumMoney = Money;
            CheckedCount = 1;

            if ((Body != "") && (CheckedCount > 0) && (SumMoney > 0))
            {
                OnlinePaymentAlipayToBank(CheckedCount, SumMoney, Body, UserDistillIDs);
            }

            //写入操作日志
            OperationLog Log = new OperationLog();

            Log._Memo = _User.Name + "处理" + e.Item.Cells[2].Text.Trim() + "日薪（处理方式：支付宝到银行）";
            Log._OpDateTime = DateTime.Now;
            Log._UserID = _User.ID;
            Log._UserIP = System.Web.HttpContext.Current.Request.UserHostAddress;

            Log.Add();
            //操作日志写入完成


            BindData1();
        }

        if (e.CommandName == "btnToAlipay")
        {
            int Count = 0;
            double SumMoney = 0;
            string Body = "";

            string UserDistillIDs = "";

            //*******************************************************
            SumMoney = ShoveEL._Convert.StrToDouble(e.Item.Cells[3].Text, 0);                      //总金额					0.01～50000.00
            Count = 1;     //批次号即该次付款总笔数
            //*********************************************************
            Body = e.Item.Cells[1].Text + "^" + e.Item.Cells[19].Text + "^" + e.Item.Cells[13].Text + "^" + e.Item.Cells[20].Text + "^日薪"; //注意格式多条用"|" 隔开 //"0039411^92781@qq.com^周长军^0.01^test|0039491^550833185@qq.com^谢凯^0.01^263"

            //写入操作日志
            OperationLog Log = new OperationLog();

            Log._Memo = _User.Name + "处理" + e.Item.Cells[2].Text.Trim() + "日薪（处理方式：支付宝到支付宝）";
            Log._OpDateTime = DateTime.Now;
            Log._UserID = _User.ID;
            Log._UserIP = System.Web.HttpContext.Current.Request.UserHostAddress;

            Log.Add();
            //操作日志写入完成

            UserDistillIDs = e.Item.Cells[1].Text;
            OnlinePaymentAlipayToAlipay(Count, SumMoney, Body, UserDistillIDs);

            return;
        }
    }

    protected void btnAlipayAdd_Click(object sender, EventArgs e)
    {
        int CheckedCount = 0;
        double SumMoney = 0;
        string Body = "";

        int i = 0;
        double Money = 0;

        string UserDistillIDs = "";

        for (i = 0; i < g1.Items.Count; i++)
        {
            CheckBox chkBox = (CheckBox)g1.Items[i].Cells[0].FindControl("cbAddAlipay");

            if (chkBox != null && chkBox.Checked)
            {
                Money = ShoveEL._Convert.StrToDouble(g1.Items[i].Cells[20].Text, 0);

                Body += g1.Items[i].Cells[1].Text.Trim() + "," + g1.Items[i].Cells[13].Text.Trim() + "," + g1.Items[i].Cells[10].Text.Trim() + "," + g1.Items[i].Cells[8].Text.Trim() + "," + g1.Items[i].Cells[11].Text.Trim() + "," + g1.Items[i].Cells[12].Text.Trim() + "," + g1.Items[i].Cells[9].Text.Trim() + "," + Money.ToString() + "," + (ShoveEL._Convert.StrToBool(g1.Items[i].Cells[18].Text.Trim(), true) ? "2" : "1") + "," + g1.Items[i].Cells[17].Text.Trim() + "\r\n";

                if (UserDistillIDs == "")
                {
                    UserDistillIDs = g1.Items[i].Cells[1].Text.Trim();
                }
                else
                {
                    UserDistillIDs += "," + g1.Items[i].Cells[1].Text.Trim();
                }

                SumMoney += Money;
                CheckedCount++;

                //写入操作日志
                OperationLog Log = new OperationLog();

                Log._Memo = _User.Name + "处理" + g1.Items[i].Cells[2].Text.Trim() + "日薪（处理方式：支付宝到银行）";
                Log._OpDateTime = DateTime.Now;
                Log._UserID = _User.ID;
                Log._UserIP = System.Web.HttpContext.Current.Request.UserHostAddress;

                Log.Add();
                //操作日志写入完成
            }
        }

        if ((Body != "") && (CheckedCount > 0) && (SumMoney > 0))
        {
            OnlinePaymentAlipayToBank(CheckedCount, SumMoney, Body, UserDistillIDs);
        }
        else
        {
            ShoveEL._Web.JavaScript.Alert(this, "您没有选中任何选项。");

            return;
        }
    }

    protected void btnAlipayToAlipayAdd_Click(object sender, EventArgs e)
    {
        int CheckedCount = 0;
        double SumMoney = 0;
        string Body = "";

        int i = 0;
        double Money = 0;

        string UserDistillIDs = "";

        for (i = 0; i < g1.Items.Count; i++)
        {
            CheckBox chkBox = (CheckBox)g1.Items[i].Cells[0].FindControl("cbAddAlipay");

            if (chkBox != null && chkBox.Checked)
            {
                Money = ShoveEL._Convert.StrToDouble(g1.Items[i].Cells[20].Text, 0);

                if (Body != "")
                {
                    Body += "|" + g1.Items[i].Cells[1].Text + "^" + g1.Items[i].Cells[19].Text + "^" + g1.Items[i].Cells[13].Text + "^" + g1.Items[i].Cells[20].Text + "^日薪";
                }
                else
                {
                    Body += g1.Items[i].Cells[1].Text + "^" + g1.Items[i].Cells[19].Text + "^" + g1.Items[i].Cells[13].Text + "^" + g1.Items[i].Cells[20].Text + "^日薪";
                }

                if (UserDistillIDs == "")
                {
                    UserDistillIDs = g1.Items[i].Cells[1].Text.Trim();
                }
                else
                {
                    UserDistillIDs += "," + g1.Items[i].Cells[1].Text.Trim();
                }

                SumMoney += Money;
                CheckedCount++;

                //写入操作日志
                OperationLog Log = new OperationLog();

                Log._Memo = _User.Name + "处理" + g1.Items[i].Cells[2].Text.Trim() + "日薪（处理方式：支付宝到支付宝）";
                Log._OpDateTime = DateTime.Now;
                Log._UserID = _User.ID;
                Log._UserIP = System.Web.HttpContext.Current.Request.UserHostAddress;

                Log.Add();
                //操作日志写入完成
            }
        }

        if ((Body != "") && (CheckedCount > 0) && (SumMoney > 0))
        {
            OnlinePaymentAlipayToAlipay(CheckedCount, SumMoney, Body, UserDistillIDs);
        }
        else
        {
            ShoveEL._Web.JavaScript.Alert(this, "您没有选中任何选项。");

            return;
        }
    }

    protected void gPager1_PageWillChange(object Sender, Shove.Web.UI.PageChangeEventArgs e)
    {
        BindData1();
    }

    private void BindData2()
    {
        DateTime dtime = ShoveEL._Convert.StrToDateTime(tbTime.Value,"");

        //DataTable dt = DAL.Views.V_UsersDistill.Select("", "(PaymentType = -30 or PaymentType = -20 or PaymentType = 1 or PaymentType = 2 or PaymentType = 3) and [Type] = 1 and (Result = 1 or Result = 2)", "isSurrogate desc");
        DataTable dt = DAL.Views.V_UserDistills.Select("", "year([Datetime]) = " + dtime.Year + " and Month([Datetime]) = " + dtime.Month + " and Day([Datetime]) = " + dtime.Day + " and PaymentType <> 0 and [Type] = 1 and (Result = 1 or Result = 2)", "isSurrogate desc");

        if (dt == null)
        {
            ShoveEL._Web.JavaScript.Alert(this.Page, "数据库连接失败");

            return;
        }

        g2.DataSource = dt;
        g2.DataBind();

        gPager2.Visible = (dt.Rows.Count > 0);
    }

    protected void g2_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
        {
            int PaymentType = ShoveEL._Convert.StrToInt(e.Item.Cells[15].Text, 0);
            int Result = ShoveEL._Convert.StrToInt(e.Item.Cells[19].Text, 0);

            e.Item.Cells[2].Text += "(" + e.Item.Cells[13].Text + ")";

            double Money = ShoveEL._Convert.StrToDouble(e.Item.Cells[3].Text, 0);
            e.Item.Cells[3].Text = "￥" + Money.ToString("N");

            int Type = ShoveEL._Convert.StrToInt(e.Item.Cells[15].Text, 0);

            if (PaymentType == 1)
            {
                e.Item.Cells[5].Text = "日薪" + " (线下转账)";
            }
            else if (PaymentType == 2)
            {
                e.Item.Cells[5].Text = "日薪" + " (在线转账到银行卡)";
            }
            else if (PaymentType == 3)
            {
                e.Item.Cells[5].Text = "日薪" + " (在线转账到支付宝)";
            }
            else if (PaymentType == -20)
            {
                e.Item.Cells[5].Text = "日薪" + " (在线转账到银行卡) -- 失败!";
            }
            else if (PaymentType == -30)
            {
                e.Item.Cells[5].Text = "日薪" + " (在线转账到支付宝) -- 失败!";
            }

            e.Item.Cells[17].Text = "日薪";

            e.Item.Cells[18].Text = "2";    //对公对私标志 1 表示对公账号 2 表示对私账号

            Button btnOK = (Button)e.Item.Cells[7].FindControl("btnOK");

            if (Result == 1)
            {
                e.Item.Cells[6].Text = "派款失败!";
            }
            else if (Result == 2)
            {
                e.Item.Cells[6].Text = "完成";
            }

            if (PaymentType != 1)
            {
                if (Result == 1)
                {
                    btnOK.Enabled = true;
                }
                else
                {
                    btnOK.Enabled = false;
                }
            }
            else
            {
                btnOK.Enabled = false;
            }
        }

        e.Item.Cells[0].Visible = false;
    }

    protected void gPager2_PageWillChange(object Sender, Shove.Web.UI.PageChangeEventArgs e)
    {
        BindData2();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        BindData2();
    }

    protected void btnDownload_Click(object sender, EventArgs e)
    {
        //BindData2();
    }

    protected void g2_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        int Result = 0;
        string Return = "";

        if (e.CommandName == "btnOK")
        {
            if (DAL.Procedures.P_UserDistillUpdate.Call(ShoveEL._Convert.StrToLong(e.Item.Cells[1].Text, 0), ShoveEL._Convert.StrToLong(e.Item.Cells[14].Text, 0), ShoveEL._Convert.StrToDouble(e.Item.Cells[20].Text, 0), _User.ID, ref Result, ref Return) < 0)
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, "数据处理失败");

                return;
            }

            if (Result < 0)
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, Return);

                return;
            }

            //写入操作日志
            OperationLog Log = new OperationLog();

            Log._Memo = _User.Name + "处理" + e.Item.Cells[2].Text + "日薪（处理方式：线下转账）";
            Log._OpDateTime = DateTime.Now;
            Log._UserID = _User.ID;
            Log._UserIP = System.Web.HttpContext.Current.Request.UserHostAddress;

            Log.Add();
            //操作日志写入完成

            BindData2();

            ShoveEL._Web.JavaScript.Alert(this.Page, "处理成功");

            return;
        }
    }

    protected void btnPanel1_Click(object sender, EventArgs e)
    {
        BindData();

        btnPanel1.Style.Add("background-color", "#E1EFFA");
        Panel1.Visible = true;
        tdPanel1.Style.Add("background-color", "#E1EFFA");

        btnPanel2.Style.Add("background-color", "#F0F0F0");
        Panel2.Visible = false;
        tdPanel2.Style.Add("background-color", "#F0F0F0");

        btnPanel3.Style.Add("background-color", "#F0F0F0");
        Panel3.Visible = false;
        tdPanel3.Style.Add("background-color", "#F0F0F0");
    }

    protected void btnPanel2_Click(object sender, EventArgs e)
    {
        BindData1();

        btnPanel1.Style.Add("background-color", "#F0F0F0");
        Panel1.Visible = false;
        tdPanel1.Style.Add("background-color", "#F0F0F0");

        btnPanel2.Style.Add("background-color", "#E1EFFA");
        Panel2.Visible = true;
        tdPanel2.Style.Add("background-color", "#E1EFFA");

        btnPanel3.Style.Add("background-color", "#F0F0F0");
        Panel3.Visible = false;
        tdPanel3.Style.Add("background-color", "#F0F0F0");
    }

    protected void btnPanel3_Click(object sender, EventArgs e)
    {
        BindData2();

        btnPanel1.Style.Add("background-color", "#F0F0F0");
        Panel1.Visible = false;
        tdPanel1.Style.Add("background-color", "#F0F0F0");

        btnPanel2.Style.Add("background-color", "#F0F0F0");
        Panel2.Visible = false;
        tdPanel2.Style.Add("background-color", "#F0F0F0");

        btnPanel3.Style.Add("background-color", "#E1EFFA");
        Panel3.Visible = true;
        tdPanel3.Style.Add("background-color", "#E1EFFA");
    }

    protected void OnlinePaymentAlipayToBank(int Count, double SumMoney, string Body, string UserDistillIDs)
    {
        //业务参数赋值；
        partner = PublicFunction.GetOptionsAsString("OnlinePay_Alipay_UserNumber", "");		//partner		合作伙伴ID			保留字段
        key = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_MD5Key", "");   //partner账户的支付宝安全校验码

        gateway = "https://www.alipay.com/cooperate/gateway.do";
        service = "bptb_pay_file";
        sign_type = "MD5";
        _input_charset = "GB2312";                                                  //编码类型
        file_digest_type = "MD5";                                                   //文件摘要算法
        biz_type = "d_sale";                                                        //业务类型

        agentID = "2088001456282873";

        ShoveEL.Alipay.Alipay ap = new ShoveEL.Alipay.Alipay();
        DateTime dtNow = DateTime.Now;

        string FileName = "";
        string FileAddr = "";
        string ZipFileName = "";
        string ZipFileAddr = "";

        int i = 0;

        if ((Body != "") && (Count > 0) && (SumMoney > 0))
        {
            string strDateTime = dtNow.ToString("yyyyMMdd");

            #region     CSV文件标准格式

            //日期,总金额,总笔数,支付宝帐号(Email)
            //20080418,10,1,53669955@qq.com
            //商户流水号,收款银行户名,收款银行帐号,收款开户银行,收款银行所在省份,收款银行所在市,收款支行名称,金额,对公对私标志,备注
            //2007052801,韦吴石,6221885511000609058,工商银行,广东省,深圳市,工商银行深圳宝安分行,10,2,2132

            #endregion

            Body = "日期,总金额,总笔数,支付宝帐号(Email)\r\n" + strDateTime + "," + SumMoney.ToString() + "," + Count.ToString() + "," + PublicFunction.GetOptionsAsString("OnlinePay_Alipay_UserName", "") + "\r\n" + "商户流水号,收款银行户名,收款银行帐号,收款开户银行,收款银行所在省份,收款银行所在市,收款支行名称,金额,对公对私标志,备注\r\n" + Body;

            System.Random rad = new Random();
            string Num = rad.Next(1, 999).ToString();
            Num = Num + dtNow.Hour.ToString() + dtNow.Minute.ToString() + dtNow.Second.ToString();
            Num = Num.PadLeft(9, '0');

            FileName = "PAPX_" + strDateTime + "_P" + Num + ".csv".ToLower();
            FileAddr = MapPath("../AlipayPayment/PABX/" + FileName).ToLower();
            ZipFileName = "PAPX_" + strDateTime + "_P" + Num + ".Zip".ToLower();
            ZipFileAddr = MapPath("../AlipayPayment/PABX/" + ZipFileName).ToLower();

            if (!System.IO.File.Exists(FileAddr))
            {
                try
                {
                    ShoveEL._IO.File.WriteFile(FileAddr, Body);
                }
                catch
                {
                    ShoveEL._Web.JavaScript.Alert(this.Page, "CSV文件写入异常");

                    return;
                }
            }
            else
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, "文件写已存在");

                return;
            }

            if (System.IO.File.Exists(FileAddr))
            {
                if (!System.IO.File.Exists(ZipFileAddr))
                {
                    try
                    {
                        ShoveEL._IO.File.Compress(FileAddr, ZipFileAddr);
                    }
                    catch
                    {
                        ShoveEL._Web.JavaScript.Alert(this.Page, "文件压缩出现异常");

                        return;
                    }
                }

            }
            else
            {
                ShoveEL._Web.JavaScript.Alert(this.Page, "CSV文件不存在");

                return;
            }
        }

        if (!System.IO.File.Exists(ZipFileAddr))
        {
            ShoveEL._Web.JavaScript.Alert(this.Page, "ZIP文件不存在");

            return;
        }

        byte[] Date = System.IO.File.ReadAllBytes(ZipFileAddr);
        digest_bptb_pay_file = ShoveEL.Alipay.Alipay.GetMD5(Date, _input_charset);

        string[] Sortedstr = ap.GetUploadParams
            (
            service,
            _input_charset,
            partner,
            file_digest_type,
            biz_type,
            agentID
            );                                                                      //签名

        // 读文件流
        FileStream fs = new FileStream(ZipFileAddr, FileMode.Open, FileAccess.Read, FileShare.Read);

        // 这部分需要完善
        string ContentType = "application/octet-stream";
        byte[] fileBytes = new byte[fs.Length];
        fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
        fs.Close();

        // 生成需要上传的二进制数组
        CreateBytes cb = new CreateBytes();
        // 所有表单数据
        ArrayList bytesArray = new ArrayList();
        // 普通表单
        string[] fields = new string[Sortedstr.Length + 1];

        char[] delimiterChars = { '=' };

        for (i = 0; i < Sortedstr.Length; i++)
        {
            string fieldName = Sortedstr[i].Split(delimiterChars)[0];
            string fieldValue = Sortedstr[i].Split(delimiterChars)[1];

            bytesArray.Add(cb.CreateFieldData(fieldName, fieldValue));
            fields[i] = fieldName + "=" + fieldValue;
        }

        bytesArray.Add(cb.CreateFieldData("digest_bptb_pay_file", digest_bptb_pay_file));
        fields[i] = "digest_bptb_pay_file=" + digest_bptb_pay_file;
        sign = AlipayCommon.GetSign(fields, key).Trim();
        bytesArray.Add(cb.CreateFieldData("sign", sign));
        bytesArray.Add(cb.CreateFieldData("sign_type", "MD5"));

        // 文件表单
        bytesArray.Add(cb.CreateFieldData("bptb_pay_file", ZipFileAddr, ContentType, fileBytes));

        // 合成所有表单并生成二进制数组
        byte[] bytes = cb.JoinBytes(bytesArray);

        //byte[] responseBytes = ShoveEL._String.Compress("上传成功");
        //bool uploaded = true;

        // 返回的内容
        byte[] responseBytes;

        // 上传到指定Url        
        bool uploaded = cb.UploadData(gateway, bytes, out responseBytes);

        string UploadResult = System.Text.Encoding.Default.GetString(responseBytes);

        if (UploadResult.IndexOf("上传成功") >= 0)
        //if (UploadResult.IndexOf("x阢騍?H?\0\a?+") >= 0)
        {
            //写入数据库（FileName）

            if (DAL.Procedures.P_UserDistillsUpdate.Call(ZipFileName, UserDistillIDs, 2, 300) < 0)
            {
                PublicFunction.WriteLogini("P_UserDistillsUpdate 过程执行失败 文件名为：" + ZipFileName);
            }

            ShoveEL._Web.JavaScript.Alert(this.Page, UploadResult + "请耐心等待处理结果！");

            BindData1();
        }
        else
        {
            try
            {
                File.Delete(FileAddr);
                File.Delete(ZipFileAddr);
            }
            catch
            {
            }

            ShoveEL._Web.JavaScript.Alert(this.Page, UploadResult);

            return;
        }

    }

    protected void OnlinePaymentAlipayToAlipay(int Count, double SumMoney, string Body, string UserDistillIDs)
    {
        //业务参数赋值；
        partner = PublicFunction.GetOptionsAsString("OnlinePay_Alipay_UserNumber", "");		//partner		合作伙伴ID			保留字段
        key = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_MD5Key", "");   //partner账户的支付宝安全校验码
        //**************e******************************************
        string email = PublicFunction.GetOptionsAsString("OnlinePay_Alipay_UserName", "");             //付款人账号
        string account_name = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_RealityName", "");		//			账户真实姓名 

        string gateway = "https://www.alipay.com/cooperate/gateway.do?";	//'支付接口
        string _input_charset = "utf-8";
        string service = "batch_trans_notify";
        string sign_type = "MD5";

        DateTime dtNow = DateTime.Now;
        string pay_date = dtNow.ToString("yyyyMMdd");   // 付款日期   //注意格式

        //*******************************************************
        System.Random rad = new Random();
        string Num = rad.Next(1, 99).ToString();
        Num = Num.PadLeft(2, '0');
        string batch_no = dtNow.ToString("yyyyMMddhhmmss") + Num;	    //批量付款订单号 日期(20070412)+16位序列号
        string batch_fee = SumMoney.ToString();                         //总金额 0.01～50000.00
        string batch_num = Count.ToString();                            //批次号即该次付款总笔数
        //*********************************************************
        string detail_data = Body;                                      //注意格式多条用"|" 隔开 //"0039411^92781@qq.com^周长军^0.01^test|0039491^550833185@qq.com^谢凯^0.01^263"
        string notify_url = ShoveEL._Web.Utility.GetSiteUrl() + "/OnlinePayment/Alipay/AlipayNotify.aspx"; //服务器通知返回接口

        //ShoveEL.Database.MSSQL.ExecuteNonQuery("update T_UserDistills set PaymentType = 3, Result = 1 where [id] in (" + UserDistillIDs + ")");
        if (DAL.Procedures.P_UserDistillsUpdate.Call("", UserDistillIDs, 3, 300) < 0)
        {
            PublicFunction.WriteLogini("P_UserDistillsUpdate 过程执行失败");
        }

        ShoveEL.Alipay.Alipay ap = new ShoveEL.Alipay.Alipay();
        string aliay_url = ap.CreatUrl(
             gateway,
             service,
             partner,
             sign_type,
             batch_no,
             account_name,
             batch_fee,
             batch_num,
             email,
             pay_date,
             detail_data,
             key,
             notify_url,
             _input_charset
            );

        Response.Redirect(aliay_url, true);                                        //可以采用表单（post）传递数据
        //this.Response.Write("<script language='javascript'>window.top.location.href='" + aliay_url + "'</script>");

        return;
    }

    protected void btnExcel_Click(object sender, EventArgs e)
    {
        if (dtExcel != null && dtExcel.Rows.Count > 0)
        {            
            dtExcel.Columns.Remove("isSurrogate");            
            dtExcel.Columns.Remove("Earning");
            dtExcel.Columns.Remove("EarningBalanced");
            dtExcel.Columns.Remove("Province");
            dtExcel.Columns.Remove("City");

            dtExcel.Columns[0].ColumnName = "序号";
            dtExcel.Columns[1].ColumnName = "会员编号";
            dtExcel.Columns[2].ColumnName = "真实姓名";
            dtExcel.Columns[3].ColumnName = "身份证号";
            dtExcel.Columns[4].ColumnName = "开户行";
            dtExcel.Columns[5].ColumnName = "银行卡号";
            dtExcel.Columns[6].ColumnName = "帐户名";
            dtExcel.Columns[7].ColumnName = "奖金总额";

            DataTableToExcel.DataTableToExcelAndDownload(dtExcel, "AdminDistillMoney.xls");
        }
        else
        {
            PublicFunction.GoError(ErrorNumber.NoData, "没有数据，不能导出到Excel!", "AdminDistillMoney");
        }
    }
}
